package com.myBlog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myBlog.constants.RedisConstants;
import com.myBlog.constants.SystemConstants;
import com.myBlog.domain.dto.AddArticleDTO;
import com.myBlog.domain.dto.ArticleDTO;
import com.myBlog.domain.entity.Article;
import com.myBlog.domain.ResponseResult;
import com.myBlog.domain.entity.ArticleTag;
import com.myBlog.domain.entity.Category;
import com.myBlog.domain.vo.ArticleDetailVo;
import com.myBlog.domain.vo.ArticleVo;
import com.myBlog.domain.vo.HotArticleVo;
import com.myBlog.domain.vo.PageVo;
import com.myBlog.mapper.ArticleMapper;
import com.myBlog.mapper.CategoryMapper;
import com.myBlog.service.ArticleService;
import com.myBlog.service.ArticleTagService;
import com.myBlog.service.CategoryService;
import com.myBlog.utils.BeanCopyUtils;
import com.myBlog.utils.RedisCache;
import com.myBlog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Resource
    CategoryMapper categoryMapper;

    @Resource
    private RedisCache redisCache;
    @Resource
    private ArticleTagService articleTagService;

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 查询热门文章
     *
     * @return
     */
    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章，封装成ResponseResult返回
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        wrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_PUBLISH);
        //按照浏览量降序排序
        wrapper.orderByDesc(Article::getViewCount);
        //只查询10个
        Page<Article> page = new Page<>(1, 10);
        this.page(page, wrapper);
        List<Article> articles = page.getRecords();
        //bean拷贝
        List<HotArticleVo> articlesVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(articlesVos);
    }

    @Override
    public ResponseResult articleList(int pageNum, int pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //1.categoryId有值，就要查询相应的category
        wrapper.eq((categoryId != null) && categoryId > 0, Article::getCategoryId, categoryId);
        //2.正式发布
        wrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_PUBLISH);
        //3.置顶的文章要在前面,isTop降序排序
        wrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, wrapper);
        //查询categoryName
        List<Article> articles = page.getRecords();

        //article去查询articleName
/*
        articles = articles.stream()
                .peek(article -> article.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());
*/

        //封装查询Vo
        List<ArticleVo> articleVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleVo.class);
        PageVo pageVo = new PageVo(articleVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 根据id查询文章信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id获取文章
        Article article = getById(id);
        //从Redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue(RedisConstants.ARTICLE_VIEWCOUNT, id.toString());
        if (viewCount != null) {
            article.setViewCount(viewCount.longValue());
        }
        //转换成Vo
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    /**
     * 修改观看数量
     *
     * @param articleId
     * @return
     */
    @Override
    public ResponseResult updateViewCount(Long articleId) {
        //更新Redis中的对应id
        redisCache.incrementCacheMapValue(RedisConstants.ARTICLE_VIEWCOUNT, articleId.toString(), 1);
        return ResponseResult.okResult();
    }

    /**
     * 添加文章
     *
     * @param articleDTO
     * @return
     */
    @Override
    @Transactional
    public ResponseResult add(AddArticleDTO articleDTO) {
        //添加博文
        Article article = BeanCopyUtils.copyBean(articleDTO, Article.class);
        article.setCreateTime(new Date());
        article.setCreateBy(SecurityUtils.getUserId());
        articleMapper.insert(article);
        List<ArticleTag> articleTags = articleDTO.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    /**
     * 文章分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param articleDTO
     * @return
     */
    @Override
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, ArticleDTO articleDTO) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(articleDTO.getTitle()), Article::getTitle, articleDTO.getTitle());
        wrapper.like(StringUtils.hasText(articleDTO.getSummary()), Article::getSummary, articleDTO.getSummary());
        wrapper.eq(null != articleDTO.getId(), Article::getId, articleDTO.getId());
        Page<Article> articlePage = new Page<>(pageNum, pageSize);
        page(articlePage, wrapper);
        PageVo pageVo = new PageVo(articlePage.getRecords(), articlePage.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    /**
     * 根据id集合删除文章
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public ResponseResult deleteById(List<Long> ids) {
        if (ids.size() > 0) {
            articleTagService.removeBatchByIds(ids);
            List<Article> articles = listByIds(ids);
            this.removeByIds(articles);
        }

        return ResponseResult.okResult();
    }

    /**
     * 修改文章内容
     *
     * @param articleDTO
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateArticleInfo(AddArticleDTO articleDTO) {
        //更新博文
        Article article = BeanCopyUtils.copyBean(articleDTO, Article.class);
        //先从redis中获取最新的viewCount
        Integer viewCount = redisCache.getCacheMapValue(RedisConstants.ARTICLE_VIEWCOUNT, article.getId().toString());
        if (viewCount != null) {
            article.setViewCount(viewCount.longValue());
        } else {
            article.setViewCount(0L);
        }
        article.setUpdateTime(new Date());
        articleMapper.updateById(article);
        List<ArticleTag> articleTags = articleDTO.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加博客和标签的关联
        articleTagService.removeBatchByIds(articleTags);
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    /**
     * 根据文章id查询文章内容
     *
     * @param articleId
     * @return
     */
    @Override
    public ResponseResult getArticleInfo(Long articleId) {
        ArticleDetailVo articleDetailVo = (ArticleDetailVo) getArticleDetail(articleId).getData();
        AddArticleDTO articleDTO = BeanCopyUtils.copyBean(articleDetailVo, AddArticleDTO.class);
        LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleTag::getArticleId, articleId);
        List<ArticleTag> articleTags = articleTagService.list(wrapper);
        List<Long> tags = articleTags.stream()
                .map(articleTag -> articleTag.getTagId())
                .collect(Collectors.toList());
        articleDTO.setTags(tags);
        return ResponseResult.okResult(articleDTO);
    }
}
